package com.qdlc.p2p.biz.task.impl;

import com.qdlc.p2p.biz.service.MovieConfigService;
import com.qdlc.p2p.biz.task.AbstractLoanTask;
import com.qdlc.p2p.biz.task.JobQueue;
import com.qdlc.p2p.biz.task.ValueEvent;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.util.BeanUtil;
import org.apache.log4j.Logger;

/**
 * 购票业务队列
 * @author ygw
 * @version 1.0
 * @date 2016年1月21日 下午5:00:29
 */
public class BuyMovieTicketsInstanceTask extends AbstractLoanTask {

	private Logger logger = Logger.getLogger(BuyMovieTicketsInstanceTask.class);

	public BuyMovieTicketsInstanceTask() {
		super();
		task.setName("BuyMovieTicketsInstanceTask.Task");
	}

	@SuppressWarnings("unchecked")
	@Override
	public void doLoan() {
		MovieConfigService movieConfigService = (MovieConfigService) BeanUtil.getBean("movieConfigService");
		JobQueue<ValueEvent> queue = JobQueue.getBuyMovieTicketsInstance();
		while (!queue.isEmpty()) {
			ValueEvent event = queue.peek();
			if (event != null) {
				String result = "success";
				try {
					// 购票业务处理
					if ("buyMovieTickets".equals(event.getOperate())) {
						movieConfigService.addColTraMovTic(event.getUserId(),event.getMoney(),event.getId(),event.getMoviePages());
					}
					if ("tppMovTicPayTrade".equals(event.getOperate())) {
						// 电影票付款
						movieConfigService.movTicpayTrade(event.getTppTradeLog());
					}
				} catch (Exception e) {
					logger.error(e.getMessage(), e);
					if (e instanceof BusinessException) {// 业务异常，保存业务处理信息
						result = e.getMessage();
					} else {
						result = "系统异常，业务处理失败";
					}
					MailUtil.sendMail("购票易业务队列异常",e);
				} finally {
					queue.remove(event);
				}
				if (event.getResultFlag() != null) {// 在需要保存系统处理信息的地方直接保存进来
					Global.TASK_RESULT_MAP.put(event.getResultFlag(), result);
				}
			}
		}
	}
}
